package com.yupi.yoj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.yupi.yoj.annotation.AuthCheck;
import com.yupi.yoj.common.BaseResponse;
import com.yupi.yoj.common.ErrorCode;
import com.yupi.yoj.common.ResultUtils;
import com.yupi.yoj.constant.UserConstant;
import com.yupi.yoj.exception.BusinessException;
import com.yupi.yoj.exception.ThrowUtils;
import com.yupi.yoj.model.dto.contest.ContestQueryTeamListByTidsRequest;
import com.yupi.yoj.model.dto.question.AddQuestionRequest;
import com.yupi.yoj.model.dto.question.QuestionQueryRequest;
import com.yupi.yoj.model.dto.question.UpdateQuestionRequestById;
import com.yupi.yoj.model.entity.Question;
import com.yupi.yoj.model.vo.QuestionVO;
import com.yupi.yoj.service.QuestionService;
import com.yupi.yoj.service.QuestionSubmitService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/question")
public class QuestionController {

    @Autowired
    QuestionService questionService;
    @Autowired
    private QuestionSubmitService questionSubmitService;

    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    BaseResponse<Question> addQuestion(AddQuestionRequest addQuestionRequest ) {
        String title = addQuestionRequest.getTitle();
        String content = addQuestionRequest.getContent();
        String judgecase = addQuestionRequest.getJudgecase();
        String ans = addQuestionRequest.getAnswer();
        if (StringUtils.isAnyBlank( title, content, judgecase, ans)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        Question question = new Question();
        BeanUtils.copyProperties(addQuestionRequest, question);
        questionService.addQuestion(question);
        return ResultUtils.success(question);
    }
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    BaseResponse<Boolean> updateQuestionById(UpdateQuestionRequestById updateQuestionRequestById ){
        Long id = updateQuestionRequestById.getId();
        String title = updateQuestionRequestById.getTitle();
        String content = updateQuestionRequestById.getContent();
        String ans = updateQuestionRequestById.getAnswer();
        if (id <= 0 || StringUtils.isAnyBlank( title, content, ans)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        Question question = new Question();
        BeanUtils.copyProperties(updateQuestionRequestById, question);
        questionService.updateQuestionById(question);
        return ResultUtils.success(true);
    }
    @DeleteMapping("/delete/{id}")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    BaseResponse<Boolean> deleteQuestionById(@PathVariable Long id) {
        if (id == null) throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        questionService.deleteQuestionById(id);
        return ResultUtils.success(true);
    }
    @GetMapping("/get/{id}")
    BaseResponse<QuestionVO> getQuestionById(@PathVariable Long id ) {
        if (id == null) throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        QuestionVO questionVO = questionService.getQuestionById(id);
        if (questionVO == null) throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "题目不存在");
        return ResultUtils.success(questionVO);
    }
    @PostMapping("/list")
    public BaseResponse<List<QuestionVO>> listQuestion() {
        List<Question> questionList = questionService.list();
        ThrowUtils.throwIf(questionList==null, ErrorCode.NOT_FOUND_ERROR, "题目库为空");
        List<QuestionVO> questionVOList = questionService.getQuestionVO(questionList);
        return ResultUtils.success(questionVOList);
    }
    /**
     * 分页获取用户列表（仅管理员）
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Question>> listQuestionByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                   HttpServletRequest request) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        return ResultUtils.success(questionPage);
    }

    /**
     * 分页获取用户封装列表
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                       HttpServletRequest request) throws JsonProcessingException {
        if (questionQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
        questionService.getQueryWrapper(questionQueryRequest));
        Page<QuestionVO> questionVOPage = new Page<>(current, size, questionPage.getTotal());
        List<QuestionVO> questionVO = questionService.getQuestionVO(questionPage.getRecords());
        questionVOPage.setRecords(questionVO);
        return ResultUtils.success(questionVOPage);
    }

    /**
     * 根据题目或标签获取题目
     */ @GetMapping("/list/{title}/{tags}")
    public BaseResponse<List<QuestionVO>> listQuestionByTagTitle(@PathVariable("tags") String tags, @PathVariable("title") String title)
    {
        if (tags.equals("_")) tags = null;
        if (title.equals("_")) title = null;

        if (tags == null && title == null) {
            return this.listQuestion();
        }
        List<QuestionVO> questionVOList = questionService.listQuestionByTagTitle(title, tags);
        return ResultUtils.success(questionVOList);
    }

    /**
     * 获取竞赛的题目列表
      */
    @PostMapping("/getQuestionList")
    public BaseResponse<List<QuestionVO>> getQuestionListByTids(@RequestBody ContestQueryTeamListByTidsRequest contestQueryRequest){
        ThrowUtils.throwIf(contestQueryRequest == null, ErrorCode.PARAMS_ERROR, "参数为空");
        List<Question> questionList = questionService.getQuestionListByTids(contestQueryRequest);
        return ResultUtils.success(questionService.getQuestionVO(questionList));
    }

    /**
     * 分页搜索（从 ES 查询，封装类）
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/search/page/vo")
    public BaseResponse<Page<QuestionVO>> searchPostVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                         HttpServletRequest request) {
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Question> postPage = questionService.searchFromEs(questionQueryRequest);
        return ResultUtils.success(questionService.getQuestionVOPage(postPage, request));
    }
}
